package com.allwees.bs.module.core.wf.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import com.allwees.bs.core.modelbase.entity.BaseEntity;
import com.allwees.bs.module.core.wf.WorkflowAware;
import com.allwees.core.common.util.EnumUtil;
import com.allwees.core.wf.Action;
import com.allwees.core.wf.FsmState;
import com.allwees.core.wf.Workflow;
import lombok.Data;
import lombok.EqualsAndHashCode;

import javax.persistence.Column;

/**
 * 独立工作流实例
 *
 * @author yangylsky
 * @since 2019-12-12
 */
@SuppressWarnings("rawtypes")
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("wf_workflow_instance")
public final class WorkflowInstance extends BaseEntity implements Workflow<FsmState, Action> {

    private static final long serialVersionUID = 3297817860908985809L;

    private String stateClassName;

    private String actionClassName;

    /**
     * 上一个操作
     */
    @Column(length = 32)
    protected String wfLatestAction;

    /**
     * 上一个状态
     */
    @Column(length = 32)
    protected String wfBackState;

    /**
     * 当前状态
     */
    @Column(length = 32)
    protected String wfState;

    /**
     * 当前流程绑定的业务对象key
     */
    @Column(length = 48)
    private String bsKey;

    @SuppressWarnings("unchecked")
    @Override
    public <S extends FsmState> S getState() {
        return (S) EnumUtil.getEnum(stateClassName, wfState);
    }

    @Override
    public void setState(FsmState state) {
        wfState = state.name();
    }

    @SuppressWarnings("unchecked")
    public <S extends FsmState> S getBackState() {
        return (S) EnumUtil.getEnum(stateClassName, wfBackState);
    }

    @SuppressWarnings("unchecked")
    public <A extends Action> A getLatestAction() {
        return (A) EnumUtil.getEnum(actionClassName, wfLatestAction);
    }

    @Override
    public void setBackState(FsmState backState) {
        wfBackState = backState.name();
    }

    @Override
    public void setLatestAction(Action latestAction) {
        wfLatestAction = latestAction.name();
    }

    @SuppressWarnings("unchecked")
    public <S extends FsmState, A extends Action> S signal(WorkflowAware wfAwareObj, A action) {
        return (S) this.signal(action);
    }
}
